import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time,sys
import plugin_helper

class VivaManager:
  
  def __init__(self):
    self.MODES=plugin_helper.enum(GET_SERIES_LIST=1,GET_EPISODES_LIST=2,PLAY=3)
  
  def work(self,mode,url='',name=''):
    if (mode==self.MODES.GET_SERIES_LIST):
      self.getSeriesList()
    elif(mode==self.MODES.GET_EPISODES_LIST):
      self.getEpisodeList(url,name)
    elif(mode==self.MODES.PLAY):
      plugin_helper.playRtmpFromUrl(url)
      
  def getSeriesList(self):
    matches = plugin_helper.getMatches("http://viva.walla.co.il/",'href="(\?w=//\d+)" onclick="Evt\(this,\d,&quot;(.*?)&quot;,\d,&quot;folder_prakim_melaim')
    for url,name in matches:
      imgPath = plugin_helper.getPath('cache','headers','viva',name+".png")
      if not os.path.exists(imgPath):
        imgPath = "DefaultFolder.png"
      plugin_helper.addDir('Viva',name,'http://viva.walla.co.il/'+url,2,{"Title": urllib.unquote(name)},imgPath)
    xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
    
  def getEpisodeList(self,url,name):
    imgPath = plugin_helper.getPath('cache','headers','viva',name+".png")
    if (not os.path.exists(imgPath) or (time.time()-os.path.getmtime(imgPath))/60/60/24 > 7):
      headerPath = plugin_helper.getMatches(url,'<img class="top_pic" src="(.*?)"')[0]
      urllib.urlretrieve(headerPath,imgPath)
    matches = self.getFromAjax(url)
    for title,img,url,subtitle in matches:
      plugin_helper.addVideo('Wallavideo',title,'','http://viva.walla.co.il/'+url,3,{'Title':title,'Tagline':subtitle},img)
  
  def getFromAjax(self,url):
    match=[]
    length = 1
    i=1
    url = url + '&page='
    while (length>0 and i<=10):
      pat='<img style="width:301px;height:170px;" class="imgcls" alt="(.*?)" title=".*?" src="(.*?)">\n\t</a></div>\n\t\t<div>\n\t\t\t<div class="title w5b mb5"><a href="(.*?)">.*?</a></div>\n\t\t\t<div class="hsubtitle oflow w3 mb5">(.*?)</div>'
      news = plugin_helper.getMatches(url+str(i),pat)
      pat='<img class="imgcls" alt="(.*?)" title=".*?" src="(.*?)"></a></div><div style="margin-top:8px;"><div class="title w3b"><a href="(.*?)">.*?</a></div><div class="hsubtitle oflow w2"><a href=".*?">(.*?)</a></div>'
      news += plugin_helper.getMatches(url+str(i),pat,True)
      length=len(news)
      match+=news
      i+=1
    return match
